﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using XinYiOffice.Common;
using System.Collections;
using System.Web;
using System.Web.Caching;
using System.Web.UI.WebControls;
using XinYiOffice.Common.Web;
using XinYiOffice.Config;

namespace XinYiOffice.Basic
{
    public class AppDataCacheServer
    {
        public static int lay = 0;

        public static int GetCliCookie()
        {
            int i = 0;

            string str = SafeConvert.ToString(CookieHelper.GetCookie("xyo_cookie_aid"));
            if (!string.IsNullOrEmpty(str))
            {
                i = SafeConvert.ToInt(DESEncrypt.Decrypt(str));
            }

            return i;
        }

        /// <summary>
        /// 当前用户id
        /// </summary>
        public static int CurrentAccountId()
        {
            return GetCliCookie();
        }

        /// <summary>
        /// 当前租户ID
        /// </summary>
        public static int CurrentTenantId()
        {
            int  _CurrentTenantId = SafeConvert.ToInt(SessionHelper.GetObject("TenantId"),0);
            if (_CurrentTenantId == 0)
            {
                _CurrentTenantId = SafeConvert.ToInt(Common.DESEncrypt.Decrypt(CookieHelper.GetCookie("xyo_cookie_tenantid")));
            }

            return _CurrentTenantId;
        }



        /// <summary>
        /// 全局菜单数据,通过Session来解决
        /// </summary>
        public static DataTable MenuTreeList()
        {
            string key = string.Format("MenuTreeList_{0}", CurrentTenantId());

            if (SessionHelper.GetObject(key) == null )
            {
                DataSet ds = new BLL.MenuTree().GetList(string.Format("TenantId={0}", CurrentTenantId()));
               
                SessionHelper.AddObject(key, ds.Tables[0]);
            }

            return (DataTable)SessionHelper.GetObject(key) as DataTable;

        }


        /// <summary>
        /// 客户 模块 所使用的所有字典数据
        /// </summary>
        public static DataTable ClientInfoDictionaryTable()
        {
            string keyid = string.Format("ClientInfo_DictionaryTable_{0}", CurrentTenantId());
            if (DataCache.GetCache(keyid) == null)
            {
                DataSet ds = DbHelperSQL.Query(string.Format("select [DisplayName],[Value],[FieldName] from vDictionaryTable where TableName='{0}' and TenantId={1} ", "ClientInfo", CurrentTenantId()));
                DataCache.SetCache(keyid, ds.Tables[0]);
                
            }
            return DataCache.GetCache(keyid) as DataTable;

        }


        /// <summary>
        /// 销售机会 所使用的所有字典数据
        /// </summary>
        public static DataTable SalesOpportunitiesDictionaryTable()
        {
            string key = string.Format("SalesOpportunities_DictionaryTable_{0}", CurrentTenantId());
            if (DataCache.GetCache(key) == null)
            {
                DataSet ds = DbHelperSQL.Query(string.Format("select  [DisplayName],[Value],[FieldName]  from vDictionaryTable where TableName='{0}' and TenantId={1} ", "SalesOpportunities", CurrentTenantId()));
                DataCache.SetCache(key, ds.Tables[0]);
             
            }
            return DataCache.GetCache(key) as DataTable;

        }


        /// <summary>
        /// 营销计划 所使用的所有字典数据
        /// </summary>
        public static DataTable MarketingPlanDictionaryTable()
        {
            string key = string.Format("MarketingPlanDictionaryTable_DictionaryTable_{0}", CurrentTenantId());
            if (DataCache.GetCache(key) == null)
            {
                DataSet ds = DbHelperSQL.Query(string.Format("select  [DisplayName],[Value],[FieldName]  from vDictionaryTable where TableName='{0}' and TenantId={1} ", "MarketingPlan", CurrentTenantId()));
                DataCache.SetCache(key, ds.Tables[0]);

            }
            return DataCache.GetCache(key) as DataTable;

        }


        /// <summary>
        /// 联系人字典
        /// </summary>
        public static DataTable ClientLiaisonsDictionaryTable()
        {
            string key = string.Format("ClientLiaisonsDictionaryTable_DictionaryTable_{0}", CurrentTenantId());
            if (DataCache.GetCache(key) == null)
            {
                DataSet ds = DbHelperSQL.Query(string.Format("select  [DisplayName],[Value],[FieldName]  from vDictionaryTable where TableName='{0}' and TenantId={1} ", "ClientLiaisons", CurrentTenantId()));
                DataCache.SetCache(key, ds.Tables[0]);
            }

            return DataCache.GetCache(key) as DataTable;

        }
        


        /// <summary>
        /// 项目相关字典表
        /// </summary>
        public static DataTable ProjectInfoDictionaryTable()
        {

            string key = string.Format("ProjectInfo_DictionaryTable_{0}", CurrentTenantId());
            if (DataCache.GetCache(key) == null)
            {
                DataSet ds = DbHelperSQL.Query(string.Format("select  [DisplayName],[Value],[FieldName]  from vDictionaryTable where TableName='{0}' and TenantId={1} ", "ProjectInfo", CurrentTenantId()));
                DataCache.SetCache(key, ds.Tables[0]);
            }

            return DataCache.GetCache(key) as DataTable;

        }


        /// <summary>
        /// 议题追踪字典表
        /// </summary>
        public static DataTable IssueTrackerDictionaryTable()
        {

            string key = string.Format("IssueTracker_DictionaryTable_{0}", CurrentTenantId());
            if (DataCache.GetCache(key) == null)
            {
                DataSet ds = DbHelperSQL.Query(string.Format("select  [DisplayName],[Value],[FieldName]  from vDictionaryTable where TableName='{0}' and TenantId={1} ", "IssueTracker", CurrentTenantId()));
                DataCache.SetCache(key, ds.Tables[0]);
               
            }
            return DataCache.GetCache(key) as DataTable;

        }


        /// <summary>
        /// 职员信息表
        /// </summary>
        public static DataTable OfficeWorkerDictionaryTable()
        {

            string key = string.Format("OfficeWorker_DictionaryTable_{0}", CurrentTenantId());
            if (DataCache.GetCache(key) == null)
            {
                DataSet ds = DbHelperSQL.Query(string.Format("select  [DisplayName],[Value],[FieldName]  from vDictionaryTable where TableName='{0}' and TenantId={1} ", "OfficeWorker", CurrentTenantId()));
                DataCache.SetCache(key, ds.Tables[0]);
               
            }
            return DataCache.GetCache(key) as DataTable;

        }
       


        /// <summary>
        /// 费用报销字典表
        /// </summary>
        public static DataTable ReimbursementExpensesDictionaryTable()
        {

            string key = string.Format("ReimbursementExpensesDictionaryTable_{0}", CurrentTenantId());
            if (DataCache.GetCache(key) == null)
            {
                DataSet ds = DbHelperSQL.Query(string.Format("select  [DisplayName],[Value],[FieldName]  from vDictionaryTable where TableName='{0}'  and TenantId={1} ", "ReimbursementExpenses", CurrentTenantId()));
                DataCache.SetCache(key, ds.Tables[0]);
                
            }
            return DataCache.GetCache(key) as DataTable;


        }
        


        /// <summary>
        /// 收款单 字典表
        /// </summary>
        public static DataTable MakeCollectionsDictionaryTable()
        {

            string key = string.Format("MakeCollectionsDictionaryTable_{0}", CurrentTenantId());
            if (DataCache.GetCache(key) == null)
            {
                DataSet ds = DbHelperSQL.Query(string.Format("select [DisplayName],[Value],[FieldName]  from vDictionaryTable where TableName='{0}'  and TenantId={1} ", "MakeCollections", CurrentTenantId()));
                DataCache.SetCache(key, ds.Tables[0]);
               
            }
            return DataCache.GetCache(key) as DataTable;


        }
        



        /// <summary>
        /// 付款单 字典表
        /// </summary>
        public static DataTable AdvicePaymentDictionaryTable()
        {
            string key = string.Format("AdvicePaymentDictionaryTable_{0}", CurrentTenantId());
            if (DataCache.GetCache(key) == null)
            {
                DataSet ds = DbHelperSQL.Query(string.Format("select  [DisplayName],[Value],[FieldName]  from vDictionaryTable where TableName='{0}' and TenantId={1} ", "AdvicePayment", CurrentTenantId()));
                DataCache.SetCache(key, ds.Tables[0]);
                
            }
            return DataCache.GetCache(key) as DataTable; ;


        }
        


        /// <summary>
        /// 工资管理 字典表
        /// </summary>
        public static DataTable PayrollControlDictionaryTable()
        {

            string key = string.Format("PayrollControlDictionaryTable_{0}", CurrentTenantId());
            if (DataCache.GetCache(key) == null)
            {
                DataSet ds = DbHelperSQL.Query(string.Format("select  [DisplayName],[Value],[FieldName]  from vDictionaryTable where TableName='{0}' and TenantId={1} ", "PayrollControl", CurrentTenantId()));
                DataCache.SetCache(key, ds.Tables[0]);
                
            }
            return DataCache.GetCache(key) as DataTable;


        }


        /// <summary>
        /// 银行帐号 字典表
        /// </summary>
        public static DataTable BankAccountDictionaryTable()
        {

            string key = string.Format("BankAccountDictionaryTable_{0}", CurrentTenantId());
            if (DataCache.GetCache(key) == null)
            {
                DataSet ds = DbHelperSQL.Query(string.Format("select  [DisplayName],[Value],[FieldName]  from vDictionaryTable where TableName='{0}' and TenantId={1} ", "BankAccount", CurrentTenantId()));
                DataCache.SetCache(key, ds.Tables[0]);
            }

            return DataCache.GetCache(key) as DataTable;


        }
        


        /// <summary>
        /// 获取省
        /// </summary>
        public static DataTable Province
        {
            get
            {
                if (DataCache.GetCache("Province") == null)
                {
                    DataSet ds = new BLL.Area().GetList(string.Format("ParentId=0"));
                    DataCache.SetCache("Province", ds.Tables[0]);
                    _province = DataCache.GetCache("Province") as DataTable;
                }

                return _province;
            }


        }
        private static DataTable _province;

        #region 菜单下拉
        public static void GetMenuTreeList(int pid, ref System.Web.UI.WebControls.DropDownList ddl)
        {
            DataRow[] dr = MenuTreeList().Select(string.Format("MenuTreeId={0}", pid));
            int Id = 0;
            int MenuTreeId = 0;


            foreach (DataRow _dr in dr)
            {
                Id = SafeConvert.ToInt(_dr["Id"], 1);
                MenuTreeId = Id;

                lay++;

                string MenuTreeName = Nex(lay, MenuTreeId, pid, SafeConvert.ToString(_dr["Name"]));
                ddl.Items.Add(new ListItem(MenuTreeName, MenuTreeId.ToString()));

                GetMenuTreeList(Id, ref ddl);

                lay--;
            }
        }

        public static string Nex(int x, int bid, int pid, string cname)
        {
            StringBuilder s = new StringBuilder();

            string kg = HttpUtility.HtmlDecode("&nbsp;");

            char nbsp = (char)0xA0;


            for (int i = 0; i < x; i++)
            {
                kg += kg;

                nbsp += nbsp;
            }

            if (pid == 0)
            {
                //s.Append("─" + cname);
                s.Append("" + cname);
            }
            else
            {
                if (!GetCustomInExist(bid))
                {
                    //不存在子级
                    s.Append(kg + "├" + cname);
                    //s.Append(nbsp + "├" + cname);

                }
                else
                {//存在子级
                    s.Append(kg + "└" + cname);
                    //s.Append(nbsp + "└" + cname);
                }


            }

            return s.ToString();
        }

        protected static bool GetCustomInExist(int pid)
        {
            DataRow[] dr = MenuTreeList().Select(string.Format("Id={0}", pid));

            if (dr.Length > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion


        /// <summary>
        /// 清除缓存,根据名称
        /// </summary>
        public static void ClearDataCacheByName(string key_name)
        {
            try
            {
                System.Web.Caching.Cache ch = HttpRuntime.Cache;
                ch.Remove(key_name);
            }
            catch
            {
            }


        }


        /// <summary>
        /// 获取所有表名
        /// </summary>
        /// <returns></returns>
        public static DataTable GetAllTableName()
        {
            DataTable dt = new DataTable();

            BasicServer bs = new BasicServer();
            dt = bs.GetAllTableName();

            return dt;
        }

        /// <summary>
        /// 获取所有列名,根据表名
        /// </summary>
        /// <param name="tablename"></param>
        /// <returns></returns>
        public static DataTable GetAllColumsByTableName(string tablename)
        {
            DataTable dt = new DataTable();
            BasicServer bs = new BasicServer();
            dt = bs.GetAllColumsByTableName(tablename);
            return dt;
        }

        /// <summary>
        /// 获取城市列表，根据省的id
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public static DataTable GetCityByPid(int pid)
        {
            return new BLL.Area().GetList(string.Format("ParentId={0}", pid)).Tables[0];
        }
    }
}
